package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.os.*
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.android.billingclient.api.*
import com.google.common.collect.ImmutableList
import com.hoow.shakoow.ProjectApplication
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.data.ReqSavePayOrderInfo
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityUserRechargeBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.payBilling.PayBillingManager


/** 用户充值页 */
@SuppressLint("CustomSplashScreen")
class UserRechargeActivity_bc : BaseActivity(), PurchasesUpdatedListener {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserRechargeBinding

    // 商品id
    private val mProductId = "shake_time_1"

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.vip_info.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserRechargeBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity")
    override fun onContentViewBinded() {
        try {
            //获取用户详情回调
            mNetworkViewModel.onGetUserInfoLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mActivityBinding.textUserDaysAfterRechargeValue.text = result.vipRemindDays
                    }
                }
            }

            // 获取商品id返回
            mNetworkViewModel.onGetPayOrderIdLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mNetworkViewModel.mPayOrderId = result.productId
                        mActivityBinding.textRechargeAmountValue.text =
                            getString(R.string.shake_you_will_pay, result.amount)
                    }
                }
            }

            // 保存支付信息返回
            mNetworkViewModel.onSavePayOrderInfoLiveData.observe(this) {
                if (it.isSuccess) {
                    Toast.makeText(this, "Pay success", Toast.LENGTH_SHORT).show()
                }
            }

            // 支付成功返回
            mNetworkViewModel.onPayOrderInfoSuccessLiveData.observe(this) {
                
            }

            // 获取用户详情
            mNetworkViewModel.getUserInfo(ReqAiBase())

            // 点击购买
            mActivityBinding.textRechargeNow.rlBuyWithGooglePay.setOnClickListener {
                printLog("PBL->startConnection")
                startConnection()
            }

            // 初始化支付
            mNetworkViewModel.getPayOrderId(ReqAiBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        // 查询购买历史
        queryPurchasesAsync()
    }

    // 输出日志
    private fun printLog(text: String) {
        runOnUiThread {
            val preText = mActivityBinding.textRechargeNowLogs.text
            val curText = "$preText\n$text"
            mActivityBinding.textRechargeNowLogs.text = curText
        }
    }

    // 保存支付信息
    private fun savePayOrderProcessInfo(pToken: String, pOrderId: String?) {
        if (pToken.isNotBlank()) {
            mNetworkViewModel.savePayOrderInfo(
                ReqSavePayOrderInfo(
                    purchaseToken = pToken,
                    purchaseOrderId = pOrderId ?: "",
                    buyId = mNetworkViewModel.mPayOrderId
                )
            )
        }
    }

    // 保存支付成功
    private fun savePayOrderSuccessInfo(pToken: String, pOrderId: String?) {
        if (pToken.isNotBlank()) {
            mNetworkViewModel.payOrderInfoSuccess(
                ReqSavePayOrderInfo(
                    purchaseToken = pToken,
                    purchaseOrderId = pOrderId ?: "",
                    buyId = mNetworkViewModel.mPayOrderId
                )
            )
        }
    }

    // 1
    private val purchasesUpdatedListener = PurchasesUpdatedListener { billingResult, purchases ->
        // To be implemented in a later section.
        println(billingResult.toString())
    }

    // 2
    private var billingClient = BillingClient.newBuilder(ProjectApplication.context)
        .setListener(purchasesUpdatedListener)
        .enablePendingPurchases()
        .build()

    // 3
    private fun startConnection() {
        billingClient.startConnection(
            object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                        // The BillingClient is ready. You can query purchases here.
                        printLog("PBL->connection state: OK")
                        println("===>startConnection: The BillingClient is ready.")
                        val supportTypeResult =
                            billingClient.isFeatureSupported(BillingClient.FeatureType.PRODUCT_DETAILS)
                        if (supportTypeResult.responseCode == BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED) {
                            println("===>startConnection: ${billingResult.toString()}")
                            printLog("PBL->use querySkuDetailsAsync")
                            querySkuDetailsAsync()
                        } else {
                            printLog("PBL->use queryProductDetailsAsync")
                            queryProductDetailsAsync()
                        }
                    } else {
                        printLog("PBL->connection state: Error: ${billingResult.toString()}")
                        println("===>startConnection: ${billingResult.toString()}")
                    }
                }

                override fun onBillingServiceDisconnected() {
                    printLog("PBL->connection state: Disconnected")
                    // Try to restart the connection on the next request to
                    // Google Play by calling the startConnection() method.
                }
            })
    }

    // 4-new version
    private fun queryProductDetailsAsync() {
        val queryProductDetailsParams =
            QueryProductDetailsParams.newBuilder()
                .setProductList(
                    ImmutableList.of(
                        QueryProductDetailsParams.Product.newBuilder()
                            .setProductId(mNetworkViewModel.mPayOrderId)
                            .setProductType(BillingClient.ProductType.INAPP)
                            .build()
                    )
                )
                .build()

        billingClient.queryProductDetailsAsync(queryProductDetailsParams) { billingResult,
                                                                            productDetailsList ->
            println("==> queryProductDetailsAsync: ${billingResult.toString()}")
            printLog("PBL->queryProductDetailsAsync state: ${billingResult.toString()}")
            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                if (productDetailsList.isNotEmpty()) {
                    printLog("PBL->queryProductDetailsAsync state: launchBillingFlow")
                    val productDetail = productDetailsList.first()
                    launchProductBillingFlow(productDetail)
                } else {
                    printLog("PBL->queryProductDetailsAsync state: no product found")
                }
            }
        }
    }

    // 4-old version
    private fun querySkuDetailsAsync() {
        val querySkuDetailsParams =
            SkuDetailsParams.newBuilder()
                .setSkusList(mutableListOf(mProductId))
                .setType(BillingClient.SkuType.INAPP)
                .build()

        billingClient.querySkuDetailsAsync(querySkuDetailsParams) { billingResult,
                                                                    skuDetailsList ->

            println("==> querySkuDetailsAsync: ${billingResult.toString()}")
            printLog("PBL->querySkuDetailsAsync state: ${billingResult.toString()}")

            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                // The BillingClient is ready. You can query purchases here.
                println("===>querySkuDetailsAsync: The BillingClient is ready.")
                skuDetailsList?.let { list ->
                    if (list.isNotEmpty()) {
                        printLog("PBL->querySkuDetailsAsync state: launchSkuBillingFlow")
                        val skuDetail = list.first()
                        launchSkuBillingFlow(skuDetail)
                    } else {
                        printLog("PBL->querySkuDetailsAsync state: no product found")
                    }
                }

                if (skuDetailsList == null) {
                    printLog("PBL->querySkuDetailsAsync state: product is null")
                }

            } else {
                println("===>querySkuDetailsAsync: ${billingResult.toString()}")
            }
        }
    }

    // 5-new version
    private fun launchProductBillingFlow(productDetails: ProductDetails) {
        // An activity reference from which the billing flow will be launched.
        val productDetailsParamsList = listOf(
            BillingFlowParams.ProductDetailsParams.newBuilder()
                // retrieve a value for "productDetails" by calling queryProductDetailsAsync()
                .setProductDetails(productDetails)
                .build()
        )

        val billingFlowParams = BillingFlowParams.newBuilder()
            .setProductDetailsParamsList(productDetailsParamsList)
            .build()

        // Launch the billing flow
        val billingResult = billingClient.launchBillingFlow(this, billingFlowParams)
        println("billingResult: ${billingResult.toString()}")
        printLog("PBL->launchBillingFlow state: ${billingResult.toString()}")
    }

    // 5-old version
    private fun launchSkuBillingFlow(skuDetails: SkuDetails) {
        // An activity reference from which the billing flow will be launched.
        val billingFlowParams = BillingFlowParams.newBuilder()
            .setSkuDetails(skuDetails)
            .build()

        // Launch the billing flow
        val billingResult = billingClient.launchBillingFlow(this, billingFlowParams)
        println("billingResult: ${billingResult.toString()}")
        printLog("PBL->launchSkuBillingFlow state: ${billingResult.toString()}")

    }

    // 6
    override fun onPurchasesUpdated(
        billingResult: BillingResult,
        purchases: MutableList<Purchase>?
    ) {
        println("billingResult: ${billingResult.toString()}")
        printLog("PBL->onPurchasesUpdated state: ${billingResult.toString()}")

        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
            for (purchase in purchases) {
                // 保存支付信息
                savePayOrderSuccessInfo(purchase.purchaseToken, purchase.orderId)

                // 处理购买成功的情况
                handlePurchase(purchase)
            }
        } else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
            // 用户取消购买
            handleUserCancelled()
        } else {
            // 处理其他错误情况
            handleError(billingResult.responseCode)
        }
    }

    private fun handlePurchase(purchase: Purchase) {
        // 处理购买成功的逻辑，例如向用户提供购买的功能或服务
        // 可以通过 purchase 对象获取购买的详细信息
        println("success: handlePurchase")

        val pState = purchase.purchaseState
        val pStateFormat = PayBillingManager.formatPurchasedCode(pState)
        printLog(pStateFormat)

        if (pState == Purchase.PurchaseState.PURCHASED) {
            val pToken = purchase.purchaseToken
            val pOrderId = purchase.orderId

            printLog("PBL->handlePurchase token: $pToken")
            printLog("PBL->handlePurchase orderId: $pOrderId")

            // 需要验证
            consumeAsync(purchase)
        }
    }

    private fun handleUserCancelled() {
        // 用户取消购买时的处理逻辑
        println("cancel: handleUserCancelled")
        printLog("PBL->handleUserCancelled")
    }

    private fun handleError(responseCode: Int) {
        // 处理其他错误情况，可以根据 responseCode 提供相应的用户反馈
        println("error: handleError: $responseCode")
        val codeMsg = PayBillingManager.formatErrorCode(responseCode)
        printLog(codeMsg)
    }

    // 7 确认消耗
    private fun queryPurchasesAsync() {
        println("queryPurchasesAsync: 查询用户的购买历史")

        if (!billingClient.isReady) {
            printLog("PBL->queryPurchasesAsync state: billingClient not ready")
            return
        }

        // 先等待一下
        showLodingDialog()

        // 查询用户的购买历史
        val params = QueryPurchasesParams.newBuilder()
            .setProductType(BillingClient.ProductType.INAPP)
            .build()

        // 开始查询
        billingClient.queryPurchasesAsync(params) { billingResult: BillingResult, purchases: MutableList<Purchase>? ->
            printLog("PBL->queryPurchasesAsync state: ${billingResult.toString()}")

            // 关闭弹框
            dismissLoadingDialog()

            // 处理交易
            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
                for (purchase in purchases) {
                    // 处理购买成功的情况
                    handlePurchase(purchase)
                }
            } else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
                // 用户取消购买
                handleUserCancelled()
            } else {
                // 处理其他错误情况
                handleError(billingResult.responseCode)
            }
        }
    }

    // 8 消耗商品
    private fun consumeAsync(purchase: Purchase) {
        printLog("PBL->consumeAsync: start")
        println("consumeAsync: start")
        // 先等待一下
        showLodingDialog()

        val consumeParams = ConsumeParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()
        val listener =
            ConsumeResponseListener { billingResult: BillingResult, purchaseToken: String ->
                // 关闭弹框
                dismissLoadingDialog()

                printLog("PBL->consumeAsync state: ${billingResult.toString()}")
                if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) {
                    val codeMsg = PayBillingManager.formatErrorCode(billingResult.responseCode)
                    printLog(codeMsg)

                    // 保存支付信息
                    savePayOrderProcessInfo(purchaseToken, purchase.orderId ?: "")
                }
            }
        billingClient.consumeAsync(consumeParams, listener)
    }
}